
var urlRoot = "http://47.104.102.188:7979";

$(function() {
    var config = getConfig();
    urlRoot = config["data"]["url_root"];
    console.log("data-url: " + urlRoot);

    regist_radio_click();

    add_sample_items();
    add_group_items();
});

/* 点击折叠项 */
var pre_item = null;
var pre_param = "";
function onclick_header(param) {
    var item =  $('#el-collapse-head-'+ param);
    //console.log(item);
    //item.addClass("is-active");

    if(pre_item != null) {
        pre_item.removeClass("is-active");
        pre_item.parent().siblings('.el-collapse-item__wrap').css("display", "none");
    }

    if(pre_param != param) {

        if(item != null) {
            item.addClass("is-active");
            item.parent().siblings('.el-collapse-item__wrap').css("display", "block");
        }

        pre_item = item;
        pre_param = param;
    }
    else
    {
        pre_item = null;
        pre_param = null;
    }

    if(param == "p3")
    {
        fill_sample_pool();
    }

    if(param == "p2")
    {
        fill_select_data();
    }

    parent.changeFrameHeight();

}

/* 所有的单选项回调处理*/
function regist_radio_click()
{
    // 参数1：分析项目类型 单选
    $("input[name=param1]").click(function(){
        switch($("input[name=param1]:checked").attr("value")){
            case "16s":
                show_param_div("#param-16s");
                $("#otu_select").html('<option value ="16s_silva132(latest)">16s_silva132(latest)</option>' +
                    ' <option value ="16S_silva128">16S_silva128</option>');
                break;
            case "18s":
                show_param_div("#param-18s");

                $("#otu_select").html('<option value="18S_silva132(latest)">18S_silva132(latest)</option>' +
                    '<option value="18S_silva128">18S_silva128</option>');
                break;
            case "ITS":
                show_param_div("#param-ITS");
                $("#otu_select").html('<option value="ITS_unite7.2(latest)">ITS_unite7.2(latest)</option>');
                break;
            case "古菌":
                show_param_div("#param-古菌");
                $("#otu_select").html('');
                break;
            default:
                break;
        }
    });

    // 参数1：选择测试区域 单选
    // 16s
    $("input[name=param1-16s]").click(function(){
        switch($("input[name=param1-16s]:checked").attr("value")){
            case "V3+V4":
                filtered_length_min = 400;
                filtered_length_max = 500;
                break;
            case "V4+V5":
                filtered_length_min = 380;
                filtered_length_max = 480;
                break;
            default:
                break;
        }
    });
    // 18s
    $("input[name=param1-18s]").click(function(){
        switch($("input[name=param1-18s]:checked").attr("value")){
            case "V4":
                filtered_length_min = 400;
                filtered_length_max = 500;
                break;
            default:
                break;
        }
    });
    // ITS
    $("input[name=param1-ITS]").click(function(){
        switch($("input[name=param1-ITS]:checked").attr("value")){
            case "ITS1":
                filtered_length_min = 250;
                filtered_length_max = 380;
                break;
            case "ITS2": // 待定
                //filtered_length_min = 400;
                //filtered_length_max = 500;
                break;
            default:
                break;
        }
    });
    // 古菌
    $("input[name=param1-古菌]").click(function(){
        switch($("input[name=param1-古菌]:checked").attr("value")){
            case "V3+V4":
                filtered_length_min = 400;
                filtered_length_max = 500;
                break;
            case "V4+V5":
                filtered_length_min = 380;
                filtered_length_max = 480;
                break;
            default:
                break;
        }
    });
}

/* 显示/隐藏具体的参数面板*/
var pre_param_div = null;
function show_param_div(id)
{
    var param_div = $(id);
    if(pre_param_div != null && pre_param_div != param_div) {
        pre_param_div.css("display", "none");
        pre_param_div = null;
    }
    if(param_div != null) {
        param_div.css("display", "block");
        pre_param_div = param_div;
    }
}


var filtered_length_min;
var filtered_length_max;
/*
function radio_filtered_length_set(pname, pvalue, min, max)
{
}
*/

/* 参数2：-----------------------------------------------------*/
var dataJson={};
var dataName="";
function fill_select_data()
{
    var user = getUserID();

    $.ajax({
        type: "POST",
        url: urlRoot + "/api/user/data/list",
        data: {login_id : user},
        dataType: "json",
        beforeSend: setRequestHeader,
        success: function(res){
            //alert(JSON.stringify(res));
            if(res.success)
            {
                dataJson = res.data;
                var list = '<option value ="">(请选择数据)</option>';
                for(var i=0; i<dataJson.length; ++i)
                {
                    var sel = "";
                    if(dataName == dataJson[i].data_name)
                        sel = "selected";

                    var li = '<option value="'+ dataJson[i].data_name + '"' + ' ' + sel + '>' + dataJson[i].data_name + '</option>';
                    list += li;

                }
                $("#select-data-list").html(list);

                select_data_option(null);
            }
            else
            {
                MessageBox("show", "发生错误", data.message);
            }

        },
        error : function (err) {
        }
    });
}

function select_format(obj)
{
    if(obj.value == "fastq-two") {
        $("#fastq-two-param").css("display", "block");
    } else {
        $("#fastq-two-param").css("display", "none");
    }
}

function select_data_option(obj)
{
    if(obj != null)
        dataName = obj.value;

    if(dataName == "")
    {
        $("#data_sample_files_template").siblings().remove();
        $("#data_sample_list").css("display", "none");
        return ;
    }

    for(var i=0; i<dataJson.length; ++i)
    {
        if(dataJson[i].data_name == dataName)
        {
            $("#data_sample_files_template").siblings().remove();

            fill_files_list(dataJson[i].data_path);
        }
    }
}


/* 选择数据样品  按钮方式-------------*/

function select_data()
{
    var user = getUserID();

    $.ajax({
        type: "POST",
        url: urlRoot + "/api/user/data/list",
        data: {login_id : user},
        dataType: "json",
        beforeSend: setRequestHeader,
        success: function(res){
            //alert(JSON.stringify(res));
            if(res.success)
            {
                dataJson = res.data;
                fill_data_list(res.data)
            }
            else
            {
                MessageBox("show", "发生错误", data.message);
            }

        },
        error : function (err) {

        }
    });


    /*dataJson = {
        "datas": [
            {
                "data_name": "data01",
                "data_path": "/home/bazc/test_data",
                "data_desc": "样本数据1，样本数据1，样本数据1，样本数据1，",
                "state": true,
                "data_files": ["data01/file01.fna", "data01/file02.fna", "data01/file03.fna"],
            },
            {
                "data_name": "data02",
                "data_path": "/my/样本数据2",
                "data_desc": "样本数据2，样本数据2，样本数据2，样本数据2，",
                "state": true,
                "data_files": ["data02/file01.fna", "data02/file02.fna"],
            },
            {
                "data_name": "data03",
                "data_path": "/my/样本数据3",
                "data_desc": "样本数据3，样本数据3，样本数据3，样本数据3，",
                "state": true,
                "data_files": ["data03/file01.fna", "data03/file02.fna", "data03/file03.fna", "data03/file04.fna",],
            }
        ]
    }

    fill_data_list(dataJson.datas);*/
}

function click_sample_list(obj)
{
    $("#data_sample_list").css("display", "none");

    var data_name = obj.innerHTML;

    for(var i=0; i<dataJson.length; ++i)
    {
        if(dataJson[i].data_name == data_name)
        {
            $("#select_data_file_name").html(data_name);

            $("#data_sample_files_template").siblings().remove();

            fill_files_list(dataJson[i].data_path);
        }
    }
}

function fill_data_list(datas)
{
    $("#data_sample_list_template").siblings().remove();

    var list =  $("#data_sample_list");
    for(var i=0; i<datas.length; ++i)
    {
        var clone_li = $("#data_sample_list_template").clone(true);
        clone_li.css("display", "block");
        clone_li.html(datas[i].data_name);
        list.append(clone_li);

    }

    list.css("display", "block");
}


// 实时获取某个数据的文件列表
function fill_files_list(data_path)
{
    $.ajax({
        url: "http://139.9.123.107:9999/api",
        type: "POST",
        contentType: 'application/json',
        data:JSON.stringify({
            cmd:"get_files_from_path",
            path:data_path, /// "/home/bazc/test_data"
        }),

        success: function(data)
        {
            if(data.status == "successful")
            {
                /*
                results = [
                    {"name": "1.fna", "type": "fna"},
                    {"name": "5.fastq", "type": "fastq"},
                    {"name": "4.fq", "type": "fastq"},
                    { "name": "2.fa","type": "fna"},
                    {"name": "3.full.fna","type": "fna"}
                ]
                */

                var list =  $("#data_sample_files");
                list.css("display", "block");

                var files =  data.results;
                //console.log(files);
                for(var j=0; j<files.length; ++j)
                {
                    var clone_div = $("#data_sample_files_template").clone(true);
                    clone_div.css("display", "block");

                    var alias = "M"+(j+1);

                    clone_div.find(".file_checkbox").attr("checked", true);
                    clone_div.find(".file_alias").val(alias);
                    clone_div.find(".file_path").val(files[j].name);

                    list.append(clone_div);
                }
            }

        }
    });
}


// 参数3：分组 -----------------------------------------------------*/
function  fill_sample_pool()
{
    //$("#sample_item_template").siblings().remove();
    //$("#group_item_template").siblings().remove();

    // 获取所有有效的数据别名
    var file_array = [];
    var files = $(".file_checkbox:checked").siblings(".file_alias");
    for(var i=0; i<files.length; ++i)
    {
        file_array.push(files[i].value);
    }

    // 将要移除的对象（ 界面上有， 但是数据别名中已经不存在了）
    var groups = $("#group_item_template").siblings();
    groups.each(function(){
        var g_items = $(this).find("[class='sample_name']");
        g_items.each(function(){
            var item_name = $(this).text();
            if(item_name != "inner-sample-template")
            {
                // 删除已经存在的
                var pos = file_array.indexOf(item_name);
                if(pos > -1)
                    file_array.splice(pos, 1);
                else
                    $(this).parent().remove();
            }
        });
    });

    // 分组池中不存在数据，要添加到采样池
    $("#sample_item_template").siblings().remove();
    for(var i=0; i<file_array.length; ++i)
    {
        add_to_sample_pool(file_array[i]);
    }

}
/*点击：样品池对象 */
function click_sample_item(item)
{
    var sample_name = item.innerText;
    add_to_group_array(sample_name);

    item.remove();
}

/* 点击：删除分组池内样品对象  */
function click_del_group_item(item) {
    var sample_name = item.parentElement.innerText;
    add_to_sample_pool(sample_name);

    item.parentElement.remove();
}

/* 添加样品池对象*/
function add_to_sample_pool(sample_name)
{
    var sample_pool = $("#sample_pool");

    var clone_item = $("#sample_item_template").clone(true);
    clone_item.css("display", "block");
    clone_item.html(sample_name);

    sample_pool.append(clone_item);

}

/* 添加分组池内样品对象*/
function add_to_group_array(sample_name)
{
    var array =  $(".group_item_radio:checked").parent().parent().find(".group_item_array");

    var clone_item = $("#group_sample_item_template").clone(true);
    clone_item.css("display", "block");

    clone_item.find(".sample_name").html(sample_name);

    array.append(clone_item);

}

/* 点击：全选 */
function click_select_all() {
    var samples = $("#sample_item_template").siblings();
    for(var i=0; i<samples.length; ++i)
    {
        add_to_group_array(samples[i].innerText);
    }

    samples.remove();
}
/* 点击：添加新组 */
function click_new_group()
{
    var group_pool = $("#group_pool");

    var clone_item = $("#group_item_template").clone(true);
    clone_item.css("display", "table");
    group_pool.append(clone_item);

    clone_item.find(".group_item_radio").attr("checked", true);

    //clone_item.attr("id", "group"+i);
}

/* 点击：删除分组 */
function click_remove_group()
{
    var group =  $(".group_item_radio:checked").parent().parent();

    var samples =  group.find(".sample_name");
    for(var i=0; i<samples.length; ++i)
    {
        if(samples[i].innerHTML != "inner-sample-template")
            add_to_sample_pool(samples[i].innerHTML);
    }

    var next = group.next();
    if(next.length > 0) {
        next.find(".group_item_radio").attr("checked", true);
    } else   {
        var prevAll = group.prevAll();
        if(prevAll.length > 1)
        {
            group.prev().find(".group_item_radio").attr("checked", true);
        }
    }

    group.remove();
}

/* 点击：恢复默认 */
function click_to_default()
{
    $("#sample_item_template").siblings().remove();
    var files =  $(".file_checkbox:checked").siblings(".file_alias");
    for(var i=0; i<files.length; ++i)
    {
        add_to_sample_pool(files[i].value);
    }

    $("#group_item_template").siblings().remove();
    click_new_group();
}

/* 参数4：-----------------------------*/
function checkNumber01(obj)
{
    /*
    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/^\./g,"");  //验证第一个字符是数字而不是.
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
     */
    var v = parseFloat(obj.value);
    if(v < 0)
        obj.value = 0;
    if(v > 1)
        obj.value = 1;
}

function checkInt(obj){
    obj.value = parseInt(obj.value);
}


/* 参数5 ：-------------------------------*/
function select_otu(obj)
{
}


//

/* 提交 -------------------------------------*/
function onclick_submit()
{
    // 项目名称
    var submitParam = {};

    submitParam.project_name = $("#project-name").val();

    // 参数1:
    submitParam.database_type = $("input[name=param1]:checked").val(); //submitParam.database_type;
    switch(submitParam.database_type)
    {
        case "16s":
            submitParam.database_type_xxx = $("input[name=param1-16s]:checked").val();//submitParam.database_type_xxx; // 待确认关键字
            break;
        case "18s":
            submitParam.database_type_xxx = $("input[name=param1-18s]:checked").val();//submitParam.database_type_xxx; // 待确认关键字
            break;
        case "ITS":
            submitParam.database_type_xxx = $("input[name=param1-ITS]:checked").val();//submitParam.database_type_xxx; // 待确认关键字
            break;
        case "古菌":
            submitParam.database_type_xxx = $("input[name=param1-古菌]:checked").val();//submitParam.database_type_xxx; // 待确认关键字
            break;
        default:
            break;
    }

    // 参数2:
    submitParam.data_format = $("#select-format").val(); //"fasta/fastq";
    submitParam.data_samples = [];
    $(".file_checkbox:checked").each(function(){
        var alias =  $(this).siblings(".file_alias").val();
        var path =  $(this).siblings(".file_path").val();
        submitParam.data_samples.push({sample_name:alias, sample_path:path});
    });

    // 参数3:
    /*
    submitParam.data_group = [
        {sample_name:"M01", group_name:"group1"},
        {sample_name:"M02", group_name:"group1"},
        {sample_name:"M03", group_name:"group2"},
        {sample_name:"M04", group_name:"group2"},
    ];
    */
    submitParam.data_group = [];
    var groups = $("#group_item_template").siblings();
    groups.each(function(){
        var g_name = $(this).find("[class='group_name el-input__inner']").val();
        var g_items = $(this).find("[class='sample_name']");
        g_items.each(function(){
            var item_name = $(this).text();
            if(item_name != "inner-sample-template")
                submitParam.data_group.push({sample_name:item_name, group_name:g_name});
        });
    });

    var def_items = $("#sample_item_template").siblings();
    def_items.each(function(){
        var item_name = $(this).text();
        submitParam.data_group.push({sample_name:item_name, group_name:"def_group"});
    })

    // 参数4:
    submitParam.cluster_otu_similarity = $("#otu_similarity").val();
    submitParam.cluster_otu_xxx = $("#otu_xxx").val();;  // 待确认关键字
    submitParam.cluster_otu_xxx1 = $("#otu_xxx1").val();; // 待确认关键字


    // 参数5:
    var otu =  $("#otu_select").val();
    //参数5: （以下内容， 根据选择项，使用某一组）
    switch (otu) {
        case "16s_silva132(latest)":
            submitParam.database_seq = "/share/nas6/pub/database/cloud/silva/v132/rep_set/rep_set_all/97/silva132_97.fna";
            submitParam.database_taxonomy = "/share/nas6/pub/database/cloud/silva/v132/taxonomy/taxonomy_all/97/taxonomy_7_levels_named.txt";
            break;
        case "16S_silva128":
            submitParam.database_seq = "/share/nas6/pub/database/cloud/silva/v128/rep_set/rep_set_all/97/97_otus.fasta";
            submitParam.database_taxonomy = "/share/nas6/pub/database/cloud/silva/v128/taxonomy/taxonomy_all/97/taxonomy_7_levels_named.txt";
            break;
        case "18S_silva132(latest)":
            submitParam.database_seq =  "/share/nas6/pub/database/silva/SILVA_132_QIIME_release/rep_set/rep_set_all/97/silva132_97.fna";
            submitParam.database_taxonomy = "/share/nas6/pub/database/silva/SILVA_132_QIIME_release/taxonomy/taxonomy_all/97/taxonomy_7_levels_named.txt";
            break;
        case "18S_silva128":
            submitParam.database_seq = "/share/nas6/pub/database/cloud/silva/v128/rep_set/rep_set_all/97/97_otus.fasta";
            submitParam.database_taxonomy = "/share/nas6/pub/database/cloud/silva/v128/taxonomy/taxonomy_all/97/taxonomy_7_levels_named.txt";
            break;
        case "ITS_unite7.2(latest)":
            submitParam.database_seq = "/share/nas6/pub/database/unite/v7.2/10_10_2017_global/sh_refs_qiime_ver7_97_s_10.10.2017.fasta";
            submitParam.database_taxonomy = "/share/nas6/pub/database/unite/v7.2/10_10_2017_global/sh_taxonomy_qiime_ver7_97_s_10.10.2017.txt";
            break;
    }

    console.log(submitParam);
}